<!DOCTYPE html>
<html>
<head>
  <title>学生信息查询</title>
  <meta charset="UTF-8">
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h2>学生信息查询</h2>
<form id="addStudentForm">
  <label>姓名：<input type="text" name="name"></label>
  <label>学号：<input type="text" name="number"></label>
  <input type="submit" value="添加">
</form>
<table border="1">
  <thead>
  <tr>
    <th>ID</th>
    <th>姓名</th>
    <th>学号</th>
    <th>操作</th>
  </tr>
  </thead>
  <tbody id="studentTable">
  </tbody>
</table>

<script>
    // 查询学生信息
    function queryStudents() {
      $.ajax({
        url: "/api/students",
        type: "GET",
        dataType: "json",
        success: function(data) {
          if (data) {
            var studentTable = $("#studentTable");
            studentTable.empty();
            $.each(data, function(index, student) {
              var deleteButton = "<button type='button' onclick='deleteStudent(" + student.id + ")'>删除</button>";
              studentTable.append("<tr><td>" + student.id + "</td><td>" + student.name + "</td><td>" + student.number + "</td><td>" + deleteButton + "</td></tr>");
            });
          }
        },
        error: function(xhr, status, error) {
          alert("查询学生信息失败：" + error);
        }
      });
    }

    // 添加学生信息
    $("#addStudentForm").submit(function(event) {
      event.preventDefault();
      var name = $("input[name='name']").val();
      var number = $("input[name='number']").val();
      $.ajax({
        url: "/api/students",
        type: "POST",
        dataType: "json",
        data: JSON.stringify({"name": name, "number": number}),
        contentType: "application/json",
        success: function() {
          alert("添加学生信息成功");
          queryStudents();
          $("#addStudentForm")[0].reset();
        },
        error: function(xhr, status, error) {
          alert("添加学生信息失败：" + error);
        }
      });
    });

    // 删除学生信息
    function deleteStudent(id) {
      $.ajax({
        url: "/api/students/" + id,
        type: "DELETE",
        dataType: "json",
        success: function() {
          alert("删除学生信息成功");
          queryStudents();
        },
        error: function(xhr, status, error) {
          alert("删除学生信息失败：" + error);
        }
      });
    }

    $(function() {
      queryStudents();
    });
</script>
</body>
</html>